package com.wwwarehouse.usercenter.fragment.business_relationship;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;

import com.wwwarehouse.common.activity.base.BaseFragment;
import com.wwwarehouse.common.bean.response.CommonClass;
import com.wwwarehouse.common.custom_widget.ClearEditText;
import com.wwwarehouse.common.custom_widget.state_layout.StateLayout;
import com.wwwarehouse.common.custom_widget.textinput.TextInputLayout;
import com.wwwarehouse.common.eventbus_event.BackListenerEvent;
import com.wwwarehouse.common.http.NoHttpUtils;
import com.wwwarehouse.common.tools.ToastUtils;
import com.wwwarehouse.usercenter.R;
import com.wwwarehouse.usercenter.constant.UserCenterConstant;
import com.wwwarehouse.usercenter.eventbus_event.BRTagsEvent;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import de.greenrobot.event.EventBus;

/**
 * Created by xiaoke.ni on 2017/10/26.
 * 新增标签
 */
public class BRAddTagsFragment extends BaseFragment implements View.OnClickListener {

    private View mView;
    private TextInputLayout mTagTil;
    private ClearEditText mTagEt;
    private Button mSureBtn;

    private int from = -1;
    private String tagUkid;
    private String tagType;
    private String tagBusinessUkid;
    private String tagParentUkid;

    public static int FROM_ADD = 0;
    public static int FROM_UPDATE = 1;


    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mView = View.inflate(getActivity(), R.layout.fragment_br_add_tags, null);
        return mView;
    }


    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initView();
        initEvent();
        initData();
    }

    private void initData() {
        from = getArguments().getInt("from");
        if (from == FROM_UPDATE) {
            if (TextUtils.isEmpty(getArguments().getString("tagName"))) {
                mSureBtn.setEnabled(false);
            } else {
                mTagEt.setText(getArguments().getString("tagName"));
                mSureBtn.setEnabled(true);
            }
        } else if (from == FROM_ADD) {
            mSureBtn.setEnabled(false);
        }
    }

    private void initView() {
        mTagTil = (TextInputLayout) mView.findViewById(R.id.tag_til);
        mTagEt = (ClearEditText) mView.findViewById(R.id.tag_et);
        mSureBtn = (Button) mView.findViewById(R.id.sure_btn);
    }

    private void initEvent() {
        mSureBtn.setOnClickListener(this);
        mTagEt.addTextChangedListener(new TextWatcher() {
            String beforeString;

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                beforeString = s.toString();
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                int length = 0;
                for (int i = 0; i < s.length(); i++) {
                    String charAt = String.valueOf(s.charAt(i));
                    if (isChinese(charAt))
                        length += 2;
                    else
                        length++;
                }
                if (length > 12) {
                    mTagEt.setText(beforeString);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() > 0) {
                    if (compileExChar(s.toString()) || s.toString().contains(" ")) {
                        mSureBtn.setEnabled(false);
                        mSureBtn.setBackground(getResources().getDrawable(R.drawable.common_btn1_noclick_shape));
                        mTagTil.setStateWrong(getString(R.string.user_br_add_tags_error_hint));
                    } else {
                        mSureBtn.setBackground(getResources().getDrawable(R.drawable.common_btn1_normal_shape));
                        mSureBtn.setEnabled(true);
                        mTagTil.setStateNormal(getString(R.string.user_br_add_tags_hint));
                    }
                } else {
                    mSureBtn.setEnabled(false);
                    mSureBtn.setBackground(getResources().getDrawable(R.drawable.common_btn1_noclick_shape));
                }
            }
        });
    }

    private boolean compileExChar(String str) {
        String limitEx = "[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";

        Pattern pattern = Pattern.compile(limitEx);
        Matcher m = pattern.matcher(str);
        return m.find();

    }

    public static boolean isChinese(String str) {
        String regEx = "[\u4e00-\u9fa5]";
        Pattern pat = Pattern.compile(regEx);
        Matcher matcher = pat.matcher(str);
        boolean flg = false;
        if (matcher.find())
            flg = true;

        return flg;
    }


    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.sure_btn) {
            if (from == FROM_UPDATE)
                updateCmTag();
            if (from == FROM_ADD)
                addCmTag();
        }

    }

    @Override
    public void setTitle() {
        if (peekFragment() instanceof BRAddTagsFragment) {
            if (from == -1)
                from = getArguments().getInt("from");
            if (from == FROM_ADD) {
                mActivity.setTitle(getString(R.string.user_br_add_tags));
            } else {
                mActivity.setTitle(getString(R.string.user_br_update_tags));
            }
        }
    }

    @Override
    public void requestDatas() {
        from = getArguments().getInt("from");
        tagUkid = getArguments().getString("tagUkid");
        tagType = getArguments().getString("tagType");
        tagBusinessUkid = getArguments().getString("tagBusinessUkid");
        tagParentUkid = getArguments().getString("tagParentUkid");
    }

    /**
     * 修改标签
     */
    private void updateCmTag() {
        Map<String, Object> map = new HashMap<>();
        map.put("tagName", mTagEt.getText().toString().trim());
        map.put("tagUkid", tagUkid);
        map.put("tagType", tagType);
        map.put("tagBusinessUkid", tagBusinessUkid);
        NoHttpUtils.httpPost(UserCenterConstant.UPDATE_CM_TAG, map, onResponseListener, 0);
    }

    /**
     * 添加标签
     */
    private void addCmTag() {
        Map<String, Object> map = new HashMap<>();
        map.put("tagName", mTagEt.getText().toString().trim());
        map.put("tagType", tagType);
        map.put("tagBusinessUkid", tagBusinessUkid);
        map.put("tagParentUkid", tagParentUkid);
        NoHttpUtils.httpPost(UserCenterConstant.ADD_CM_TAG, map, onResponseListener, 0);
    }

    private NoHttpUtils.OnResponseListener onResponseListener = new NoHttpUtils.OnResponseListener() {
        @Override
        public void onSucceed(CommonClass commonClass, int what) {
            switch (what) {
                case 0:
                    if (TextUtils.equals("0", commonClass.getCode())) {
                        if (from == FROM_UPDATE) {
                            ToastUtils.showToastAtTop(getString(R.string.user_br_update_success));
                            EventBus.getDefault().post(new BRTagsEvent("BRCFDTagsUpdateFragment"));
                        } else if (from == FROM_ADD) {
                            ToastUtils.showToastAtTop(getString(R.string.user_br_add_success));
                            EventBus.getDefault().post(new BRTagsEvent("BRCFDTagsFragment"));
                        }
                        popFragment();
                    } else {
                        ToastUtils.showToastAtTop(commonClass.getMsg());
                    }
                    break;
            }
        }

        @Override
        public void onFailed(String s, int i) {

        }

        @Override
        public void onFinish(int i) {
            dismissProgressDialog();
        }
    };

    public void onEventMainThread(BackListenerEvent event) {
        String message = event.getMsg();
        if (message.equals("BRAddTagsFragment")) {
            if (from == FROM_UPDATE) {
                EventBus.getDefault().post(new BRTagsEvent("BRCFDTagsUpdateFragment"));
            } else if (from == FROM_ADD) {
                EventBus.getDefault().post(new BRTagsEvent("BRCFDTagsFragment"));
            }
            popFragment();
        }
    }
}
